import {
	getThreadsApi,
	getBackupStatusApi,
	getSlaveStatusApi,
} from '@utils/apis'

module.exports = function loadDbDatas() {
	$.dbMonitorJQ.threads = $.dbMonitorJQ.threads || {}

	let result = Promise.all([getThreadsApi(), getBackupStatusApi(), getSlaveStatusApi()])
	return result.then(res => {
		let threadsMap = threadsHandler(res[0])
		let backupMap = threadsHandler(res[1])
		let slaveMap = threadsHandler(res[2])
		return {
			threadsMap,
			backupMap,
			slaveMap,
		}
	})
}

function taskBackupHandler(backupArr) {
	let backupMap = {}
	for (let backup of backupArr) {
		let {
			hostname,
			backup_status,
		} = backup
		let icon = 'fa fa-camera-retro #spin middle'
		backupMap[hostname] = {
			title: `Backup ${backup_status}`,
			cls: backup_status == 'Running!' ? icon.replace('#spin', 'fa-spin') : icon.replace('#spin', ''),
			color: backup_status == 'Error!' ? 'red' : 'white'
		}
	}
	return backupMap
}

function taskSlaveHandler(slaveArr) {
	let slaveMap = {}
	for (let slave of slaveArr) {
		let {
			info,
			status,
			hostname,
		} = slave
		let icon = status == 'normal!' ? 'fa fa-cog fa-spin' : 'fa fa-cog'
		slaveMap[hostname] = {
			info,
			cls: `${icon}' console.log_${status}`,
		}
	}
	return slaveMap
}

function threadsHandler(threadsArr) {
	let dbThreads = $.dbMonitorJQ.threads
	let threadsMap = {}
	for (let thr of threadsArr) {
		let hostname = thr && thr[0] || ''
		let collectTime = thr && thr[1] || ''
		let dl = thr && thr[2] && thr[2].split(",") || []
		let idx = dl.length > 16 ? dl.length - 16 : 0
		let dataList = dl.filter((val, idx) => dl.length > 16 ? idx - 16 > 0 : true)
			.map(val => parseInt(val))
		let curThreadsNum = dataList[dataList.length - 2];
		let prevThreadsNum = dataList[dataList.length - 3];
		let retinaMode = window.devicePixelRatio > 1
		threadsMap[hostname] = {
			hostname,
			collectTime,
			dataList,
			curThreadsNum,
			prevThreadsNum,
			retinaMode,
			cls: curThreadsNum < prevThreadsNum ? "fa fa-arrow-down" : "fa fa-arrow-up",
		}
		let threadOptions = {
			type: 'bar',
			height: retinaMode ? '90' : '45',
			barWidth: retinaMode ? '7' : '3',
			barSpacing: '3',
			chartRangeMin: 0,
			chartRangeMax: 70,
			barColor: '#ffffff',
			negBarColor: '#eeeeee'
		}
		dbThreads[`threadChart${hostname}`] = dbThreads[`threadChart${hostname}`] || $(`.thread-chart-${hostname}`)
		dbThreads[`threadChart${hostname}`].sparkline(dataList, threadOptions)
	}
	delete $.dbMonitorJQ.threads
	return threadsMap
}